<?use pft\Prod\Product;
include_once('common/autoload.php');
if(!$_SESSION['memberID']){exit("<script>window.location='dlogin.html'</script>");}

$did=$_REQUEST['did']; // 分销商 ID
$sid=$_SESSION['sid']; // 会员 ID

$set_pris=$_REQUEST["set_pris"]; // 配置价格
$src_pris=$_REQUEST["src_pris"]; // 会员分销价

$pids_arr = array_unique(array_values($_REQUEST['src_pids']));// 页面所有产品
$pids_str = implode(',',$pids_arr);

// 1.先删除页面上显示的产品的所有记录
$size = count($pids_arr);
$sql="select id,pid,aids from `pft_p_apply_evolute` where sid=$sid and fid=$did and pid in ($pids_str)";
$sql="delete from `pft_p_apply_evolute` where sid=$sid and fid=$did and pid in ($pids_str) limit $size";
$GLOBALS['le']->query($sql);

// 2.给设置的产品加上购买的权限
$setPri = array();
foreach($set_pris as $key=>$price){
	$tmp = explode('_',$key);
	$pid = $tmp[0];
	$aid = $tmp[1];
	if(!isset($set_pris[$key])) continue;// 没有设置价格
	if(isset($setPri[$pid])) continue;// 已经为该分销商设置了一个转分销链
	$sql="select id,status,aids,lvl,sourceid from `pft_p_apply_evolute` where fid=$sid and sid=$aid and pid=$pid limit 1";

	$GLOBALS['le']->query($sql);
	$GLOBALS['le']->fetch_assoc();
	$aids_n = $GLOBALS['le']->f('aids').','.$sid;
	$lvl_n = $GLOBALS['le']->f('lvl') + 1;
	$sourceid = $GLOBALS['le']->f('sourceid');
	$ins = "insert into `pft_p_apply_evolute` set aids='$aids_n',sourceid=$sourceid,lvl=$lvl_n,status=0,sid=$sid,fid=$did,pid=$pid,rectime=now()";
	if($GLOBALS['le']->query($ins)){// 新增权限
		$setPri[$pid] = $aid;// 多个供应商只允许转分销一个
	};
}

// 3.配置价格
if(count($setPri)){
	
	$exis = $exis_u = $exis_uid = array();
	$pids = array_keys($setPri);
	$sql="select pid,id,tid from `uu_priceset` where pid=$did and aid=$sid and tid in (".implode(',',$pids).")";
	$GLOBALS['le']->query($sql);
	while($row=$GLOBALS['le']->fetch_assoc()){
		$exis[$row['tid']] = $row['tid'];// 获取已配置价格的产品 id 
		$exis_uid[$row['tid']]        = $row['id'];
	}
	
	foreach($setPri as $pid=>$aid){// $aid 为账号的上级供应商
		// echo $pid;
		$pk = $pid.'_'.$aid;
		$new_price = $set_pris[$pk]; // 新设置的价格
		$sup_price = $src_pris[$pk]; // 会员分销商
		$diff = $new_price - $sup_price;
		if($diff<0) continue;// 给分销商的价格比自己还低，X
		$diff = $diff*100;
		if(isset($exis[$pid])){
			$uid = $exis_uid[$pid];
			$sql="update `uu_priceset` set dprice=$diff where id=$uid limit 1";			
			
		}else{// 给分销商设置价格

			$sql="insert into `uu_priceset` set dprice=$diff,tid=$pid,pid=$did,aid=$sid";
		}
		echo $sql;
		$GLOBALS['le']->query($sql);
	}
}



echo "<script>alert('配置成功!')</script>";
exit;
?>